﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System;
using OfficeOpenXml;
using System.Linq;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace NetDiskStorageWebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ExcelUploadController : ControllerBase
    {
        [HttpPost("upload")]
        public async Task<IActionResult> UploadExcel(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("请上传一个有效的文件。");
            }

            try
            {
                var orders = new List<LogisticsOrder>();

                // 设置 EPPlus 的 LicenseContext
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

                // 读取 Excel 文件
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var package = new ExcelPackage(stream))
                    {
                        var worksheet = package.Workbook.Worksheets[0]; // 假设数据在第一个工作表中
                        var rowCount = worksheet.Dimension.Rows; // 总行数

                        for (int row = 2; row <= rowCount; row++) // 从第2行开始读取，跳过标题行
                        {
                            var order = new LogisticsOrder
                            {
                                OrderNumber = worksheet.Cells[row, 1].Text,
                                CustomerName = worksheet.Cells[row, 16].Text,
                                TrackingNumber = worksheet.Cells[row, 17].Text
                            };

                            orders.Add(order);
                        }
                    }
                }

                return Ok(new { Message = "文件上传并解析成功！", Data = orders });
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"文件处理失败：{ex.Message}");
            }
        }
        
    }

    public class LogisticsOrder
    {
        public string OrderNumber { get; set; }
        public string CustomerName { get; set; }
        /// <summary>
        /// 快递单号
        /// </summary>
        public string TrackingNumber { get; set; }
    }
}
